import os
import twitter
import tkMessageBox
from Tkinter import *
from twitter import *
from urllib2 import *

class Login(Frame):
    def login(self):
        return twitter.Api(self.eu.get(), self.ep.get())
    
    def get_save(self):
        api = self.login()      
        save_path = os.path.join(os.getcwd(), 'twitter_backup.log')
        f = open(save_path, 'w')
        f.write(' no.         id                 name\n')
        no = 1
        try:
            statuses = api.GetFriends()
        except (TwitterError, HTTPError) as e:
              tkMessageBox.showerror('Error', 'Username or password error!')
              return
        for status in statuses:
            line = str(no).rjust(4) + ' ' + str(status.id).rjust(10) + ' ' + status.screen_name.rjust(20) + '\n'
            f.write(line)
            no += 1
        f.close()
        tkMessageBox.showinfo('Finished', "Friends' list has been saved to file: " + save_path)
        
    def about(self):
        tkMessageBox.showinfo('About', 'author : http://twitter.com/cugfeng\n'
                                     + 'version: 0.1\n'
                                     + 'date     : Jun 20, 2009\n'
                                     + 'Based on Python-Twitter(http://code.google.com/p/python-twitter/)\n')
        
    def create_widgets(self):
        self.menu = Menu(self)
        self.master.config(menu=self.menu)
        self.help_menu = Menu(self.menu, tearoff=0)
        self.help_menu.add_command(label='About', command=self.about)
        self.menu.add_cascade(label='Help', menu=self.help_menu)
        
        Label(self, text='Username:').grid(row=0)
        Label(self, text='Password:').grid(row=1)
        
        self.eu = Entry(self)
        self.eu.grid(row=0, column=1)
        self.ep = Entry(self, show='*')
        self.ep.grid(row=1, column=1)
        
        Button(self, text='Get & Save', command=self.get_save).grid(row=2)
        Button(self, text='Quit', command=quit).grid(row=2, column=1, sticky=E)

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()

root = Tk()
login = Login(master=root)
login.master.title('Twitter Backup')
login.master.minsize(210, 60)
login.master.resizable(False, False)
login.master.protocol('WM_DELETE_WINDOW', quit)
login.mainloop()
root.destroy()
